#include "vxanchor.h"

VxAnchor::VxAnchor(QWidget * controlled, QWidget * paper, Type type) :
		QObject(), _type(type), _paperw(paper), _objectw(controlled),
		_objectType(Widget)
{
	paper->installEventFilter(this);
	controlled->installEventFilter(this);
	_storeObject();
}


VxAnchor::VxAnchor(QGraphicsProxyWidget * controlled, QGraphicsView * paper, Type type) :
		QObject(), _type(type), _paperi(paper), _objecti(controlled),
		_objectType(GraphicsItem)
{
	paper->installEventFilter(this);
	controlled->installEventFilter(this);
	_storeObject();
}

QPoint VxAnchor::_getXY()
{
	switch(_objectType){
	case GraphicsItem:{
			QPoint vp = _paperi->mapFromScene(_objecti->pos());
			return vp;
		}

	case Widget:{
			return _objectw->pos();
		}
	}
	return QPoint();
}


void VxAnchor::_setXY(QPoint xy)
{
	switch(_objectType){
	case GraphicsItem:{
			QPointF vp = _paperi->mapToScene(xy);
			_objecti->setPos(vp);
			break;
		}

	case Widget:{
			return _objectw->move(xy);
			break;
		}
	}
}

QSize VxAnchor::_getPaperSize()
{
	int w;
	int h;

	switch(_objectType){
	case GraphicsItem:{
			w = _paperi->viewport()->width();
			h = _paperi->viewport()->height();
			break;
		}

	case Widget:{
			w = _paperw->width();
			h = _paperw->height();
		}
	}
	return QSize(w, h);
}


void VxAnchor::_storeObject()
{
	QPoint p = _getXY();

	QSize sz = _getPaperSize();

	if (p.x() < sz.width()/2){
		_position.setX(p.x());
	} else {
		_position.setX(p.x() - sz.width());
	}

	if (p.y() < sz.height()/2){
		_position.setY(p.y());
	} else {
		_position.setY(p.y() - sz.height());
	}
	qDebug() << _position;
}


bool VxAnchor::eventFilter(QObject * obj, QEvent * event)
{
	if (obj == _objecti || obj == _objectw){
		if (event->type() == QEvent::Move || event->type() == QEvent::GraphicsSceneMove){
			_storeObject();
		}
	} else
	if (obj == _paperi || obj == _paperw){
		if (event->type() == QEvent::Resize){
			QPoint p = _getXY();
			int mx = p.x();
			int my = p.y();
			QSize sz = _getPaperSize();
			if (_position.x() < 0){
				mx = sz.width() + _position.x();
			}
			if (_position.y() < 0){
				my = sz.height() + _position.y();
			}
			_setXY(QPoint(mx, my));
		}
	}

	return QObject::eventFilter(obj, event);
}
